﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Xml;
using Command.Model;
using NJGZBTYHXT.Properties;
using Common.Excel;
using System.Diagnostics;

namespace NJGZBTYHXT
{
    public partial class Atsyh : Form
    {
        #region 字段与属性

        private FirstOption xh;
        private DataGridView _dgv;
        public DataGridView Dgv
        {
            get { return _dgv; }
            set { _dgv = value; }
        }
        /// <summary>
        /// 摇号总数
        /// </summary>
        private int _yhCount = 0;
        /// <summary>
        /// 摇号总数
        /// </summary>
        public int YhCount { get { return _yhCount; } set { _yhCount = value; } }
        /// <summary>
        /// 摇号每次数
        /// </summary>
        private int _yhMcCount = 0;
        /// <summary>
        /// 摇号每次数
        /// </summary>
        public int YhMcCount { get { return _yhMcCount; } set { _yhMcCount = value; } }

        /// <summary>
        /// 已摇号次数
        /// </summary>
        private int _forEndCount = 0;
        /// <summary>
        /// 摇号次数
        /// </summary>
        private int _forCount = 0;

        /// <summary>
        /// 随机数组类实例
        /// </summary>
        RandomArray yh;

        /// <summary>
        /// 结果序号数组
        /// </summary>
        private int[] jg;
        /// <summary>
        /// 结果序号数组
        /// </summary>
        public int[] Jg
        {
            get { return jg; }
            set { jg = value; }
        }

        /// <summary>
        /// 结果序号列表
        /// </summary>
        private ArrayList yclist;

        /// <summary>
        /// 已选列表
        /// </summary>
        public ArrayList Yclist
        {
            get { return yclist; }
            set { yclist = value; }
        }

        #endregion

        public Atsyh()
        {
            InitializeComponent();
            //this.dataGridView1.RowPostPaint += new DataGridViewRowPostPaintEventHandler(Program.dataGridView1_RowPostPaint);
        }

        /// <summary>
        /// 开始|停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (_forEndCount <= 0)
            {
                if (textBox1.Text.Trim() == "")
                {
                    textBox1.Focus();
                    MessageBox.Show("请输入摇号总数", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if (textBox2.Text.Trim() == "")
                {
                    textBox2.Focus();
                    MessageBox.Show("请输入每次摇号数", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }

                //获取摇号总数
                _yhCount = int.Parse(textBox1.Text.Trim());

                //获取每次摇号数量
                _yhMcCount = int.Parse(textBox2.Text.Trim());

                if (_yhMcCount > _yhCount)
                {
                    textBox2.Focus();
                    MessageBox.Show("每次摇号数不能大于摇号总数", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }

                yh.MaxValue = _dgv.Rows.Count - 1;
                
                dataGridView1.Visible = true;

                textBox1.Enabled = textBox2.Enabled = false;


                if (_yhCount % _yhMcCount > 0)
                {
                    _forCount = _yhCount / _yhMcCount + 1;
                }
                else
                {
                    _forCount = _yhCount / _yhMcCount;
                }

                ///开启候选
                if (xh.IsOpen)
                {
                    //获取候选列表
                    int[] listIndexs = xh.SelectData(_dgv);

                    jg = yh.Start(_yhCount, listIndexs);

                    jg = RandomArray.SortByJumble(jg);
                }
                else
                {
                    jg = yh.Start(_yhCount);
                }

                yclist.Clear();
                foreach (int index in jg)
                {
                    yclist.Add(index);
                }
            }

            if (button1.Text != "开始")
            {
                button1.Text = "开始";

                button1.Image = Resources.play_l;

                timer1.Enabled = false;

                _forEndCount++;

                if (_forEndCount >= _forCount)
                {
                    button1.Image = Resources.play_h;
                    button1.Enabled = false;
                }

                button5.Enabled = button2.Enabled = button3.Enabled = button4.Enabled = true;

                int viewCount = 0;

                dataGridView1.Rows.Clear();

                while (yclist.Count > 0)
                {
                    if (viewCount < _yhMcCount)
                    {
                        int index = int.Parse(yclist[0].ToString());

                        object[] values = new object[_dgv.Rows[0].Cells.Count + 1];

                        DataGridViewRow row = _dgv.Rows[index];

                        if (row != null)
                        {
                            for (int z = 0; z < row.Cells.Count; z++)
                            {
                                values[z] = row.Cells[z].Value;
                            }

                            dataGridView1.Rows.Add(values);

                            yclist.RemoveAt(0);
                        }
                        viewCount++;
                    }
                    else
                    {
                        break;
                    }
                }

                LoadText();
            }
            else
            {
                if (_dgv.Rows.Count > 0)
                {
                    button1.Text = "停止";
                    button1.Image = Resources.stop_h;
                    timer1.Enabled = true;
                    button5.Enabled = button2.Enabled = button3.Enabled = button4.Enabled = false;
                }
                else
                {
                    MessageBox.Show("系统提示：没有检索到数据源", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }

        private void LoadText()
        {
            int gbze = 0, sbze = 0;

            foreach (int index in jg)
            {
                DataGridViewRow row = _dgv.Rows[index];
                int gb = int.Parse(row.Cells["国补总额（元）"].Value.ToString());
                int sb = int.Parse(row.Cells["省补总额（元）"].Value.ToString());
                gbze += gb;
                sbze += sb;
            }
            toolStripStatusLabel1.Text = string.Format("摇号次数:{0}/{1}  摇出条数:{2}  国补总额(元):{3}  省补总额(元):{4}", _forEndCount, _forCount, _yhCount - yclist.Count, gbze, sbze);
        }

        /// <summary>
        /// 生成Excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Application.StartupPath + @"\Excel\";

                if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

                string filePath = path + DateTime.Now.ToFileTime() + ".xls";

                FirstOption.OutExcel(dataGridView1, filePath);

                if (DialogResult.OK == MessageBox.Show("生成Excel成功，文件路径为：\n" + filePath + "\n是否打开文件？", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Process.Start(filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示");
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 开始摇号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Rows.Clear();

                int[] sjjg = new int[_yhMcCount];

                sjjg = yh.Start(_yhMcCount);

                for (int i = 0; i < sjjg.Length; i++)
                {
                    int index = sjjg[i];

                    object[] values = new object[_dgv.Rows[index].Cells.Count + 1];

                    for (int z = 0; z < _dgv.Rows[index].Cells.Count; z++)
                    {
                        values[z] = _dgv.Rows[index].Cells[z].Value;
                    }

                    dataGridView1.Rows.Add(values);
                }
            }
            catch (Exception ex)
            {
                timer1.Enabled = false;
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Atsyh_Load(object sender, EventArgs e)
        {
            xh = new FirstOption();

            yh = new RandomArray();
            yh.MaxValue = _dgv.Rows.Count - 1;
            yh.MinValue = 0;

            jg = new int[_yhCount];

            yclist = new ArrayList();

            foreach (DataGridViewColumn dgvr in _dgv.Columns)
            {
                dataGridView1.Columns.Add(dgvr.Name, dgvr.HeaderText);
            }

            dataGridView1.Columns["ID"].DisplayIndex = 0;

            FirstOption.DataGridViewSHC(dataGridView1, "ID,姓名,证件号码,国补总额（元）,省补总额（元）", true, true);

            dataGridView1.Visible = false;
        }

        /// <summary>
        /// 查看结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            YHJG yhjg = new YHJG();
            yhjg.dgv = dataGridView1;
            yhjg.ShowDialog(this);
        }

        private void Atsyh_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timer1.Enabled = false;
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 确认完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\excel\";

            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            string filePath = path + DateTime.Now.ToFileTime() + ".xls";

            DataTable dtSource = new DataTable();

            NPOIHelper.ListColumnsName = new SortedList(new MyComparer());

            string[] cs = new string[] { 
                        "id", "市", "县", "乡镇", "村", "地址", "受益户身份", "手机号码", "姓名", "性别", "联系电话", "证件号码", "出生日期", "文化程度", 
                        "主要农作物", "耕地面积", "机具大类", "机具小类", "机具品目", "机具型号", "机具编号", "指标确认书编号", "数量", "特殊设备数量", 
                        "生产企业", "单台国补（元）", "国补总额（元）", "单台省补（元）", "省补总额（元）", "单台市补（元）", "单台县补（元）", "备注", 
                        "状态", "录入日期" };

            foreach (string csname in cs)
            {
                Common.Excel.NPOIHelper.ListColumnsName.Add(csname, csname);
            }

            foreach (DataGridViewColumn column in _dgv.Columns)
            {
                dtSource.Columns.Add(column.Name);
            }

            foreach (int index in jg)
            {
                DataGridViewRow row = _dgv.Rows[index];
                object[] values = new object[dtSource.Columns.Count];
                for (int i = 0; i < dtSource.Columns.Count; i++)
                {
                    values[i] = row.Cells[dtSource.Columns[i].ColumnName].Value;
                }
                dtSource.Rows.Add(values);
            }

            NPOIHelper.ExportExcel(dtSource, filePath);

            xh.Delete();

            if (DialogResult.Yes == MessageBox.Show("确认退出该窗口吗？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                this.Close();
                //Process.Start(filePath);
            }
        }
    }
}
